
// 页面加载完成后执行
$(document).ready(function () {
    initFileUploads();
    initFormSubmit();
    initModal();
    initPage();
    bindEvents();
    loadDanmakuByPage(1);
});

/**
 * 初始化页面基础数据
 */
function initPage() {
    loadDanmakuCount();
    loadBlockedDanmakuCount();
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 绑定筛选按钮点击事件
    const filterBtn = document.getElementById('filterBtn');
    if (filterBtn) {
        filterBtn.addEventListener('click', function () {
            const keyword = document.getElementById('keywordFilter').value;
            const timeRange = document.getElementById('timeRange').value;
            const videoTitle = document.getElementById('videoFilter').value;

            filterParams.keyword = keyword;
            filterParams.timeRange = timeRange;
            filterParams.videoTitle = videoTitle;

            loadDanmakuByPage(1);
        });
    }
}

/**
 * 加载指定页码的弹幕数据
 * @param {number} pageNum 页码
 */
function loadDanmakuByPage(pageNum) {
    currentPage = pageNum;

    $.ajax({
        type: "GET",
        url: "danmaku.do",
        data: {
            pageNum: pageNum,
            keyword: filterParams.keyword,
            timeRange: filterParams.timeRange,
            videoTitle: filterParams.videoTitle
        },
        success: function (data) {
            if (data.code === 200) {
                const page = data.data;
                totalPages = page.pages;

                // 渲染弹幕列表
                renderDanmakuList(page.list);

                // 渲染分页控件
                renderPagination(pageNum, totalPages);
            }
        },
        error: function (xhr, status, error) {
            console.error("加载弹幕数据失败:", error);
        }
    });
}

/**
 * 渲染弹幕列表
 * @param {Array} danmakuList 弹幕列表
 */
function renderDanmakuList(danmakuList) {
    const danmuList = document.querySelector('.danmu-list');
    danmuList.innerHTML = `
        <div class="danmu-header">
            <div class="header-content">弹幕内容</div>
            <div class="header-video">所属视频</div>
            <div class="header-time">发送时间</div>
            <div class="header-status">状态</div>
            <div class="header-actions">操作</div>
        </div>
    `;

    danmakuList.forEach(function (danmaku) {
        const statusText = danmaku.status === DANMAKU_STATUS.APPROVED ? '已通过' : '已屏蔽';
        const actionBtn = danmaku.status === DANMAKU_STATUS.APPROVED ?
            `<button onclick="blockDanmaku(${danmaku.id})">屏蔽</button>` :
            `<button onclick="approveDanmaku(${danmaku.id})">通过</button>`;

        const danmuItem = document.createElement('div');
        danmuItem.classList.add('danmu-item');
        danmuItem.innerHTML = `
            <div class="item-content">${danmaku.content}</div>
            <div class="item-video">${danmaku.videoTitle}</div>
            <div class="item-time">${danmaku.sendTime}</div>
            <div class="item-status">${statusText}</div>
            <div class="item-actions">${actionBtn}</div>
        `;

        danmuList.appendChild(danmuItem);
    });
}

/**
 * 渲染分页控件
 * @param {number} currentPage 当前页码
 * @param {number} totalPages 总页数
 */
function renderPagination(currentPage, totalPages) {
    const pageNumbers = document.querySelector('.page-numbers');
    pageNumbers.innerHTML = '';

    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement('div');
        pageBtn.classList.add('page-btn');
        if (i === currentPage) {
            pageBtn.classList.add('active');
        }
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', function () {
            loadDanmakuByPage(i);
        });
        pageNumbers.appendChild(pageBtn);
    }

    const prevBtn = document.querySelector('.prev-btn');
    const nextBtn = document.querySelector('.next-btn');

    prevBtn.disabled = currentPage === 1;
    nextBtn.disabled = currentPage === totalPages;

    prevBtn.addEventListener('click', function () {
        if (currentPage > 1) {
            loadDanmakuByPage(currentPage - 1);
        }
    });

    nextBtn.addEventListener('click', function () {
        if (currentPage < totalPages) {
            loadDanmakuByPage(currentPage + 1);
        }
    });
}

/**
 * 加载弹幕总数
 */
function loadDanmakuCount() {
    $.ajax({
        type: "GET",
        url: "countDanmaku.do",
        data: {
            upId: upId
        },
        success: function (data) {
            if (data.code === 200) {
                const danmakuCount = document.getElementById('danmakuCount');
                danmakuCount.textContent = data.data;
            }
        },
        error: function (xhr, status, error) {
            console.error("加载弹幕总数失败:", error);
        }
    });
}

/**
 * 加载屏蔽弹幕数
 */
function loadBlockedDanmakuCount() {
    $.ajax({
        type: "GET",
        url: "countBlockedDanmaku.do",
        data: {
            upId: upId
        },
        success: function (data) {
            if (data.code === 200) {
                const danmakuDownCount = document.getElementById('danmakuDownCount');
                danmakuDownCount.textContent = data.data;
            }
        },
        error: function (xhr, status, error) {
            console.error("加载屏蔽弹幕数失败:", error);
        }
    });
}

/**
 * 通过弹幕
 * @param {number} id 弹幕ID
 */
function approveDanmaku(id) {
    $.ajax({
        type: "POST",
        url: "approveDanmaku.do",
        data: {
            id: id
        },
        success: function (data) {
            if (data.code === 200) {
                alert(`弹幕 #${id} 已通过审核`);
                loadDanmakuByPage(currentPage);
            } else {
                alert(`操作失败：${data.message}`);
            }
        },
        error: function (xhr, status, error) {
            console.error("通过弹幕审核失败:", error);
            alert('网络错误，请稍后再试');
        }
    });
}

/**
 * 屏蔽弹幕
 * @param {number} id 弹幕ID
 */
function blockDanmaku(id) {
    $.ajax({
        type: "POST",
        url: "blockDanmaku.do",
        data: {
            id: id
        },
        success: function (data) {
            if (data.code === 200) {
                alert(`弹幕 #${id} 已被屏蔽`);
                loadDanmakuByPage(currentPage);
            } else {
                alert(`操作失败：${data.message}`);
            }
        },
        error: function (xhr, status, error) {
            console.error("屏蔽弹幕失败:", error);
            alert('网络错误，请稍后再试');
        }
    });
}